package cn.hcbycloud.auth.service;

import cn.hcbycloud.auth.mapper.TenantMapper;
import cn.hcbycloud.auth.model.Tenant;
import cn.hcbycloud.common.core.exception.CustomizeException;
import cn.hcbycloud.common.core.properties.TenantProperties;
import cn.hcbycloud.common.mvc.model.AppTenant;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

/**
 * 租户信息表
 *
 * @author gaoheng
 * @date 2022-01-20 16:21:41
 */
@Slf4j
@Service("tenantService")
@AllArgsConstructor
@Order(Ordered.HIGHEST_PRECEDENCE)
public class TenantService extends ServiceImpl<TenantMapper, Tenant> {
    private TenantMapper tenantMapper;

    /**
     * 添加租户信息
     *
     * @param tenantProperties
     * @return
     */
    public String addTenantInfo(TenantProperties tenantProperties) {
        Tenant tenant = new Tenant();
        tenant.setTenantCode(tenantProperties.getCode());
        tenant.setTenantName(StrUtil.isBlank(tenantProperties.getName()) ? tenantProperties.getCode() : tenantProperties.getName());
        tenant.preInsert();
        tenantMapper.insert(tenant);
        return tenant.getId();
    }

    /**
     * 查询数据库中的租户对象
     *
     * @param tenantProperties
     * @return
     */
    public AppTenant getTenantByCode(TenantProperties tenantProperties) {
        if (StrUtil.isBlank(tenantProperties.getCode())) {
            throw new CustomizeException("系统全局配置信息为空");
        }
        QueryWrapper<Tenant> wrapper = new QueryWrapper<>();
        wrapper.eq("tenant_code", tenantProperties.getCode()).last("limit 1");
        Tenant tenantObj = tenantMapper.selectOne(wrapper);
        if (ObjectUtil.isNotNull(tenantObj)) {
            return new AppTenant(tenantObj.getId(), tenantObj.getTenantName(), tenantObj.getTenantCode());
        }
        return null;
    }

    /**
     * 认证中心的租户信息不能通过配置文件提前定义，因此需要该方法根据接口入参创建
     * @param tenantCode
     * @return
     */
    public AppTenant getTenantByRequireCode(String tenantCode) {
        TenantProperties tenantProperties = new TenantProperties();
        tenantProperties.setCode(tenantCode);
        AppTenant appTenantObj = this.getTenantByCode(tenantProperties);
        if (ObjectUtil.isNull(appTenantObj)) {
            String tenantId = this.addTenantInfo(tenantProperties);
            return new AppTenant(tenantId, tenantCode, tenantCode);
        } else {
            return appTenantObj;
        }
    }
}
